Page({
  data: {
    activity: null,
    remote_src: getApp().globalData.remote_src,
    userInfo: getApp().globalData.userInfo,
    replyTo: null,  // 当前回复的评论
    showReplyInput: false,  // 是否显示回复输入框
    comments: [],
    currentPage: 1,
    isRefreshing: false,
    hasMore: true,
    isLiked: false,
    // 新增底部弹窗相关数据
    showActionSheet: false,
    selectedCommentId: null,
    selectedComment: null
  },
  
  // 新增：长按评论处理
  onCommentLongPress(e) {
    const comment = e.currentTarget.dataset.comment;
    const commentId = e.currentTarget.dataset.commentId;
    
    // 检查是否有删除权限（评论作者或活动发布者）
    const canDelete = comment.user.id === this.data.userInfo.id || 
                    this.data.activity.created_user_id === this.data.userInfo.id;
    
    if (canDelete) {
      // 触发震动反馈
      wx.vibrateShort();
      
      this.setData({
        showActionSheet: true,
        selectedCommentId: commentId,
        selectedComment: comment
      });
    }
  },

  // 新增：隐藏底部弹窗
  hideActionSheet() {
    this.setData({
      showActionSheet: false,
      selectedCommentId: null,
      selectedComment: null
    });
  },

  // 新增：阻止事件冒泡
  stopPropagation() {
    // 阻止事件冒泡，防止点击弹窗内容时关闭弹窗
  },

  // 修改现有的deleteComment函数
  deleteComment(e) {
    const commentId = e.currentTarget.dataset.commentId || this.data.selectedCommentId;
    // console.log(commentId)
    // 先隐藏弹窗
    this.hideActionSheet();
    
    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条评论吗？',
      success: (res) => {
        if (res.confirm) {
          // 发送删除请求
          wx.request({
            url: getApp().globalData.onlineService + '/api/comment/comment',
            method: 'DELETE',
            header: {
              'content-type': 'application/json',
              'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
            },
            data: {
              comment_id: commentId
            },
            success: (res) => {
              console.log(res)
              if (res.data.code === 200) {
                wx.showToast({
                  title: '删除成功',
                  icon: 'success'
                });
                // 重新加载评论列表
                this.setData({
                  comments: [],
                  currentPage: 1,
                  hasMore: true
                });
                this.loadComments(this.data.activity.id);
              } else {
                wx.showToast({
                  title: res.data.msg || '删除失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络请求失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },
  scrollToComment(commentId) {
    // 创建节点查询器
    console.log("start scroll");
    console.log(`#comment-${commentId}`)
    const query = wx.createSelectorQuery();
    // 查找指定评论
    query.select(`#comment-${commentId}`).boundingClientRect();
    query.selectViewport().scrollOffset();
    // 执行查询
    query.exec((res) => {
      console.log(res);
      if (res[0]) {
        console.log(res[0]);
        // 滚动到评论位置
        wx.pageScrollTo({
          scrollTop: res[1].scrollTop + res[0].top - 100, // 减去100px的偏移，让评论显示在更好的位置
          duration: 300
        });
      }
    });
  },
  navigateToOther(e) {
    const user = e.currentTarget.dataset.user;
    const userInfo = JSON.parse(JSON.stringify(user));
    // 对 interests 进行编码
    userInfo.interests = encodeURIComponent(JSON.stringify(userInfo.interests));
    wx.navigateTo({
      url: `/pages/other/other?userInfo=${encodeURIComponent(JSON.stringify(user))}`,
      fail: (err) => {
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },
  toggleLike() {
     // 准备请求数据
     const data = {
      activity_id: this.data.activity.id
    };

    if (!this.data.isLiked) {
      // 添加收藏
      wx.request({
        url: getApp().globalData.onlineService + '/api/fav/fav',
        method: 'POST',
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
        },
        data: data,
        success: (res) => {
          if (res.data.code === 200) {
            this.setData({
              isLiked: true
            });
            wx.showToast({
              title: '收藏成功',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: res.data.msg || '收藏失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    } else {
      // 取消收藏
      wx.request({
        url: getApp().globalData.onlineService + '/api/fav/fav',
        method: 'DELETE',
        header: {
          'content-type': 'application/json',
          'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
        },
        data: data,
        success: (res) => {
           console.log(res)
          if (res.data.code === 200) {
            this.setData({
              isLiked: false
            });
            wx.showToast({
              title: '已取消收藏',
              icon: 'success'
            });
          } else {
            wx.showToast({
              title: res.data.msg || '取消收藏失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.showToast({
            title: '网络请求失败',
            icon: 'none'
          });
        }
      });
    }
  },
  onReachBottom() {
    if (!this.data.hasMore) {
      wx.showToast({
        title: '没有更多评论了',
        icon: 'none'
      });
      return;
    }

    const nextPage = this.data.currentPage + 1;
    this.loadComments(this.data.activity.id, nextPage);
  },
  onRefresh() {
    this.setData({ isRefreshing: true });
    // 重置到第一页
    this.setData({ currentPage: 1 });
    this.loadComments(this.data.activity.id, 1);
  },
  onLoad(options) {
    const { id } = options;
    this.loadActivityDetail(id);
  },
  handleImageError(e) {
    const type = e.currentTarget.dataset.type;
    console.log(`${type} 图片加载失败`);
  },
  handleInputFocus() {
    this.setData({
      isInputFocused: true
    });
  },
  chooseImage() {
    wx.chooseMedia({
      count: 1,
      mediaType: ['image'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePath = res.tempFiles[0].tempFilePath;
        this.uploadImage(tempFilePath);
      }
    });
  },
  uploadImage(tempFilePath) {
    wx.showLoading({
      title: '上传中...',
    });
    wx.uploadFile({
      url: getApp().globalData.onlineService + '/api/infra/file',
      filePath: tempFilePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      success: (res) => {
        const data = JSON.parse(res.data);
        if (data.code === 200) {
       
          // 拼接完整的图片URL
          const imageUrl = getApp().globalData.onlineService + '/api/infra/file' + "?filename=" + data.filename;
          console.log('上传成功', imageUrl);
          this.setData({
            'commentImage': imageUrl
          });
        } else {
          wx.showToast({
            title: '上传失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '上传失败',
          icon: 'none'
        });
      },
      complete: () => {
        wx.hideLoading();
      }
    });
  },
  onCommentTap(e) {
    const comment = e.currentTarget.dataset.comment;
    console.log(comment);
    this.setData({
      replyTo: comment,
      showReplyInput: true,
      isInputFocused: true
    });
    console.log(this.data.replyTo);
  },
  handleInputBlur() {
    console.log('input blur');

    this.setData({
      isInputFocused: false,
    //  showReplyInput: false,
      replyTo: null
    });
    console.log(this.data.replyTo);
    console.log(this.data.isInputFocused);
  },
    // 删除评论图片
    deleteCommentImage() {
      this.setData({
        commentImage: ''
      });
    },
    // ... existing code ...
    submitComment() {
      const content = this.data.commentText;
      const image = this.data.commentImage;
  
      // 检查是否有文字或图片内容
      if (!content && !image) {
        wx.showToast({
          title: '请输入内容或上传图片',
          icon: 'none'
        });
        return;
      }
  
      // 构建评论数据
     
      const commentData = {
        parent_id: this.data.replyTo ? this.data.replyTo.id : -1,
        activity_id: this.data.activity.id,
        user_id: getApp().globalData.userInfo.id,
      };
      // 只有当内容不为空时才添加到 commentData
      if (content) {
        commentData.content = content.trim();
      }
      // 只有当图片不为空时才添加到 commentData
      if (image) {
        commentData.image = image;
      }
      console.log('提交的评论数据:', commentData);
      // TODO: 发送评论到服务器
      // 发送评论到服务器
      wx.request({
          url: getApp().globalData.onlineService + '/api/comment/comment',
          method: 'POST',
          header: {
            'content-type': 'application/json',
            'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
          },
          data: commentData,
          success: (res) => {
            console.log(res.data);
            if (res.data.code === 200) {
              // 评论成功，将新评论添加到评论列表
              const newComment = {
                id: res.data.msg.id,
                content: content,
                image: image,
                created_at: res.data.msg.created_at,
                parent_id: commentData.parent_id,
                user: {
                  id: getApp().globalData.userInfo.id,
                  name: getApp().globalData.userInfo.name,
                  photo_url: getApp().globalData.userInfo.photo_url
                }
              };

              // 更新评论列表
              let comments = this.data.comments || [];
              if (commentData.parent_id === -1) {
                // 添加新的顶级评论
                comments.unshift(newComment);
              } else {
               // 查找根评论
                let rootComment = null;
                for (let comment of comments) {
                  if (comment.id === commentData.parent_id) {
                    // 如果回复的是顶级评论
                    rootComment = comment;
                    break;
                  } else if (comment.replies) {
                    // 如果回复的是二级评论，查找其所属的顶级评论
                    for (let reply of comment.replies) {
                      if (reply.id === commentData.parent_id) {
                        rootComment = comment;
                        break;
                      }
                    }
                    if (rootComment) break;
                  }
                }

                // 将回复添加到根评论的回复列表中
                if (rootComment) {
                  rootComment.replies = rootComment.replies || [];
                  rootComment.replies.push(newComment);
                }
              }

              // 更新页面数据
              this.setData({
                comments: comments,
                commentText: '',
                commentImage: '',
                replyTo: null,
                showReplyInput: false
              });

              wx.showToast({
                title: '评论成功',
                icon: 'success'
              });
            } else {
              wx.showToast({
                title: res.data.msg || '评论失败',
                icon: 'none'
              });
            }
          },
          fail: () => {
            wx.showToast({
              title: '网络请求失败',
              icon: 'none'
            });
          }
        });
      // 清空输入
      this.setData({
        commentText: '',
        commentImage: '',
        replyTo: null,
        showReplyInput: false
      });
    }, 
  loadUserInfo(userId) {
    const websiteUrl = getApp().globalData.onlineService + '/api/girls/girls';
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        'user_id': userId
      },
      success: (res) => {
        if (res.data.code === 200) {
          console.log(res.data.data);
          // 更新活动创建者信息
          const activity = this.data.activity;
          activity.creator = res.data.data;
          this.setData({ activity });
        } else {
          console.log('获取用户信息失败:', res.data.msg);
        }
      },
      fail: () => {
        console.log('获取用户信息请求失败');
      }
    });
  },
  loadActivityDetail(id) {
    const websiteUrl = getApp().globalData.onlineService + '/api/activity/activity';
    wx.request({
      url: websiteUrl,
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        'activity_id': id
      },
      success: (res) => {
        if (res.data.code === 200) {
          console.log(res.data.data);
          this.setData({
            activity: res.data.data,
            isLiked: res.data.data.is_favorited // 从后端返回的数据中获取收藏状态
          });
          // 获取创建者信息
          if (res.data.data.created_user_id) {
            this.loadUserInfo(res.data.data.created_user_id);
          }
          // 加载评论数据
         this.loadComments(id);
        } else {
          wx.showToast({
            title: res.data.msg || '获取活动详情失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  loadComments(activityId, page = 1, pageSize = 10) {
    console.log(activityId, page);
    wx.request({
      url: getApp().globalData.onlineService + '/api/comment/comment',
      method: 'GET',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        'activity_id': activityId,
        'page': page,
        'page_size': pageSize
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 将评论重组为树形结构
          console.log(res.data.data.comments);
          const comments = res.data.data.comments || [];
          const commentMap = new Map();
          const rootComments = this.data.comments || [];

          // 第一步：建立评论ID到评论对象的映射
          comments.forEach(comment => {
            comment.replies = [];
            commentMap.set(comment.id, comment);
          });

          // 第二步：找到每个评论的根评论
          comments.forEach(comment => {
            if (comment.parent_id === -1) {
              // 如果是顶级评论，直接加入根评论列表
              rootComments.push(comment);
            } else {
              // 如果是回复评论，找到其根评论
              let currentComment = comment;
              let rootFound = false;
              
              while (!rootFound) {
                const parentComment = commentMap.get(currentComment.parent_id);
                // console.log(parentComment);
                if (parentComment.parent_id === -1) {
                  // 找到根评论或找不到父评论时
                  rootFound = true;
                  if (parentComment) {
                    // 将当前评论添加到根评论的回复列表中
                    parentComment.replies.push(comment);
                  } else {
                    // 找不到父评论时，将当前评论作为顶级评论
                    rootComments.push(comment);
                  }
                } else {
                  currentComment = parentComment;
                }
              }
            }
          });

          // // 按时间倒序排序
          // rootComments.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
          
          // // 对每个评论的回复也进行时间排序
          // rootComments.forEach(comment => {
          //   comment.replies.sort((a, b) => new Date(b.created_at) - new Date(a.created_at));
          // });

          // this.setData({
          //   comments: rootComments,
          //   commentTotal: res.data.data.total || 0
          // });
          console.log(rootComments)
          // 更新评论列表
          if (page === 1) {
            // 第一页直接替换
            this.setData({
              comments: rootComments,
              currentPage: 1
            });
          } else {
            // 追加新评论
            this.setData({
              comments: rootComments,
              currentPage: page
            });
          }
          console.log(comments.length === pageSize)
          // 判断是否还有更多评论
          this.setData({
            hasMore: comments.length === pageSize,
            isRefreshing: false
          });
        } else {
          console.log('获取评论失败:', res.data.msg);
          this.setData({ isRefreshing: false });
        }
      },
      fail: () => {
        console.log('获取评论请求失败');
      }
    });
  },
  joinActivity() {
    // 检查用户是否登录
    if (!getApp().globalData.userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
      // 检查用户是否已实名认证
    if (getApp().globalData.userInfo.is_auth !== 1) {
        wx.showModal({
          title: '实名认证提示',
          content: '参加活动需要先进行实名认证，是否前往认证？',
          success: (res) => {
            if (res.confirm) {
              // 跳转到实名认证页面
              wx.navigateTo({
                url: '/pages/cerficate/cerficate'
              });
            }
          }
        });
        return;
    }
    // 检查活动状态
    if (this.data.activity.status !== 0) {
      wx.showToast({
        title: '活动不可报名',
        icon: 'none'
      });
      return;
    }
  
    // 发起报名请求
    wx.request({
      url: getApp().globalData.onlineService + '/api/reg/reg',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
      },
      data: {
        activity_id: this.data.activity.id
      },
      success: (res) => {
        if (res.data.code === 200) {
          // 报名成功，更新活动状态和参与者列表
          const currentJoiners = this.data.activity.joiners_ids || [];
          const userId = getApp().globalData.userInfo.id.toString();
          
          if (!currentJoiners.includes(userId)) {
            currentJoiners.push(userId);
          }
          
          this.setData({
            'activity.is_registered': 0,
            'activity.joiners_ids': currentJoiners
          });
          wx.showToast({
            title: '报名成功',
            icon: 'success'
          });
        } else {
          console.log(res.data.msg);
          wx.showToast({
            title: res.data.msg || '报名失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },
  cancelActivity() {
    // 检查用户是否登录
    if (!getApp().globalData.userInfo) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      });
      return;
    }
    wx.showModal({
      title: '确认取消',
      content: '确定要取消报名吗？',
      success: (res) => {
        if (res.confirm) {
          // 发起取消报名请求
          wx.request({
            url: getApp().globalData.onlineService + '/api/reg/reg',
            method: 'DELETE',
            header: {
              'content-type': 'application/json',
              'Authorization': `Bearer ${getApp().globalData.userInfo.token}`
            },
            data: {
              activity_id: this.data.activity.id
            },
            success: (res) => {
              if (res.data.code === 200) {
                 // 取消报名成功，更新活动状态和参与者列表
                 const currentJoiners = this.data.activity.joiners_ids || [];
                 const userId = getApp().globalData.userInfo.id.toString();
                 
                 const index = currentJoiners.indexOf(userId);
                 if (index > -1) {
                   currentJoiners.splice(index, 1);
                 }
                 
                 this.setData({
                   'activity.is_registered': 1,
                   'activity.joiners_ids': currentJoiners
                 });
                 
                 wx.showToast({
                   title: '已取消报名',
                   icon: 'success'
                 });
              } else {
                wx.showToast({
                  title: res.data.msg || '取消报名失败',
                  icon: 'none'
                });
              }
            },
            fail: () => {
              wx.showToast({
                title: '网络请求失败',
                icon: 'none'
              });
            }
          });
        }
      }
    });
},
  onShareAppMessage() {
    return {
      title: this.data.activity.title,
      path: '/pages/activity/detail/detail?id=' + this.data.activity.id,
      imageUrl: this.data.activity.images[0] // 使用活动的第一张图片作为分享图片
    };
  }
});